package com.hxzon.netty.statistics.server;

import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.hxzon.netty.statistics.service.StatisticsClientService;
import com.hxzon.netty.statistics.util.StatisticsClientUtil;

public class StatisticsServerHandler extends SimpleChannelUpstreamHandler {

    private static final Logger logger = LoggerFactory.getLogger(StatisticsServerHandler.class);
    private StatisticsClientService statisticsClientService;

    public StatisticsServerHandler(ApplicationContext spring) {
        this.statisticsClientService = spring.getBean(StatisticsClientService.class);
    }

    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
        logger.debug("connect:" + getRemoteIp(ctx));
    }

    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
        logger.debug("disconnect:" + getRemoteIp(ctx));
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        String msg = (String) e.getMessage();
        logger.debug("收到信息:" + msg);
        e.getChannel().write("0").addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                //future.getChannel().close();
            }
        });
        //
        StatisticsClientUtil.dealwithMessage(msg, getRemoteIp(ctx), statisticsClientService);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        logger.debug("", e.getCause());
        e.getChannel().close();
    }

    private String getRemoteIp(ChannelHandlerContext ctx) {
        String remoteIp = ctx.getChannel().getRemoteAddress().toString();
        int index = remoteIp.indexOf(':');
        return remoteIp.substring(1, index);
    }
}
